<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <up-icon name="arrow-left" size="32"></up-icon>
      </view>
      <view class="title">确认订单</view>
    </view>

    <!-- 订单号信息 -->
    <view class="order-number">
      <text class="label">订单编号：</text>
      <text class="value">{{ orderNumber }}</text>
    </view>

    <!-- 商品信息（不含图片） -->
    <view class="product-info">
      <view class="product-details">
        <view class="product-title">{{ productInfo.title }}</view>
        <view class="product-price">¥{{ productInfo.price }}</view>
      </view>
    </view>

    <!-- 地址信息 -->
    <view class="address-section" @click="selectAddress">
      <view class="section-header">
        <text class="section-title">收货地址</text>
        <up-icon name="arrow-right" size="24" color="#999"></up-icon>
      </view>

      <view class="address-info" v-if="selectedAddress">
        <view class="address-name-phone">
          <text class="address-name">{{ selectedAddress.userName }}</text>
          <text class="address-phone">{{ selectedAddress.telNumber }}</text>
        </view>
        <view class="address-detail">
          {{ selectedAddress.provinceName }}{{ selectedAddress.cityName }}{{ selectedAddress.countyName }}{{ selectedAddress.detailInfo }}
        </view>
      </view>

      <view class="no-address" v-else>
        <text>请选择收货地址</text>
      </view>
    </view>

    <!-- 优惠券选择 -->
    <view class="coupon-section">
      <view class="section-header" @click="toggleCouponList">
        <text class="section-title">优惠券</text>
        <view class="coupon-selected">
          <text v-if="selectedCoupon">已选 {{ selectedCoupon.discount }}元优惠券</text>
          <text v-else>暂无可用优惠券</text>
          <up-icon :name="showCouponList ? 'arrow-up' : 'arrow-down'" size="24" color="#999"></up-icon>
        </view>
      </view>

      <!-- 优惠券列表 -->
      <view class="coupon-list" v-if="showCouponList">
        <view v-if="coupons.length === 0" class="no-coupon">
          <text>暂无可用优惠券</text>
        </view>

        <view
            class="coupon-item"
            v-for="(coupon, index) in coupons"
            :key="coupon.id"
            @click="selectCoupon(index)"
        >
          <view class="coupon-left">
            <text class="coupon-amount">¥{{ coupon.discount }}</text>
            <text class="coupon-desc">满{{ coupon.minSpend }}可用</text>
          </view>
          <view class="coupon-right">
            <text class="coupon-time">有效期至 {{ coupon.endDate }}</text>
            <up-icon
                size="24"
                color="#ff4500"
                v-if="selectedCoupon && selectedCoupon.id === coupon.id"
            ></up-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 快递方式选择（横向排列） -->
    <view class="shipping-section">
      <view class="section-header">
        <text class="section-title">快递方式</text>
      </view>

      <view class="shipping-options">
        <view
            class="shipping-option"
            v-for="(shipping, index) in shippingMethods"
            :key="shipping.id"
            @click="selectShippingMethod(index)"
        >
          <view class="shipping-info">
            <text class="shipping-name">{{ shipping.name }}</text>
            <text class="shipping-fee">¥{{ shipping.fee }}</text>
          </view>
          <up-icon
              size="28"
              color="#ff4500"
              v-if="selectedShippingIndex === index"
          ></up-icon>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-summary">
      <view class="summary-item">
        <text class="summary-label">商品总价</text>
        <text class="summary-value">¥{{ productInfo.price }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">运费</text>
        <text class="summary-value">¥{{ selectedShippingMethod.fee }}</text>
      </view>
      <view class="summary-item">
        <text class="summary-label">优惠券折扣</text>
        <text class="summary-value">-¥{{ selectedCoupon ? selectedCoupon.discount : 0 }}</text>
      </view>
      <view class="summary-total">
        <text class="summary-label">实付款</text>
        <text class="summary-value">¥{{ calculateTotal() }}</text>
      </view>
    </view>

    <!-- 底部支付栏 -->
    <view class="bottom-bar">
      <view class="total-amount">
        <text class="total-label">实付款:</text>
        <text class="total-value">¥{{ calculateTotal() }}</text>
      </view>
      <button class="pay-btn" @click="submitOrder" :disabled="!selectedAddress">
        立即支付
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, computed } from 'vue';

const { proxy } = getCurrentInstance();

// 接收从商品详情页传递的商品信息
const productInfo = ref({
  id: '',
  title: '',
  price: '0.00',
  userId: '', // 卖家ID
  createTime: ''
});

// 订单号（前端临时生成，实际由后端生成）
const orderNumber = ref('');

// 订单状态
const selectedAddress = ref(null);
const showCouponList = ref(false);
const coupons = ref([]);
const selectedCoupon = ref(null);
const shippingMethods = ref([
  { id: 1, name: '普通快递', fee: 10 },
  { id: 2, name: '顺丰速运', fee: 20 },
  { id: 3, name: '自提', fee: 0 }
]);
const selectedShippingIndex = ref(0);

// 计算属性
const selectedShippingMethod = computed(() => {
  return shippingMethods.value[selectedShippingIndex.value];
});

// 初始化页面
onMounted(() => {
  // 生成临时订单号（格式：ORD + 时间戳 + 随机数，实际由后端生成）
  generateOrderNumber();

  // 接收商品详情页传递的商品信息
  const eventChannel = proxy.getOpenerEventChannel();
  eventChannel.on('acceptProductData', (data) => {
    productInfo.value = data.productInfo;
    // 模拟获取优惠券（实际应根据商品ID和用户ID从后端获取）
    fetchCoupons();
  });
});

// 生成临时订单号（前端测试用）
const generateOrderNumber = () => {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
  orderNumber.value = `ORD${timestamp}${random}`;
};

// 地址选择（使用原生API）
const selectAddress = () => {
  uni.chooseAddress({
    success: (res) => {
      selectedAddress.value = res;
    },
    fail: (err) => {
      console.error('选择地址失败:', err);
      if (err.errMsg.includes('auth deny')) {
        uni.showModal({
          title: '提示',
          content: '需要获取您的地址权限才能继续',
          success: (res) => {
            if (res.confirm) {
              uni.openSetting();
            }
          }
        });
      }
    }
  });
};

// 优惠券相关方法
const fetchCoupons = () => {
  // 模拟接口请求（实际应根据商品价格和用户ID从后端获取）
  setTimeout(() => {
    coupons.value = [
      { id: 1, discount: 5, minSpend: 50, endDate: '2025-12-31' },
      { id: 2, discount: 10, minSpend: 100, endDate: '2025-11-30' }
    ];
  }, 500);
};

const toggleCouponList = () => {
  showCouponList.value = !showCouponList.value;
};

const selectCoupon = (index) => {
  const coupon = coupons.value[index];
  if (parseFloat(productInfo.value.price) >= coupon.minSpend) {
    selectedCoupon.value = coupon;
    showCouponList.value = false;
  } else {
    uni.showToast({
      title: `满${coupon.minSpend}元可用`,
      icon: 'none'
    });
  }
};

// 快递方式选择
const selectShippingMethod = (index) => {
  selectedShippingIndex.value = index;
};

// 计算金额
const calculateTotal = () => {
  const subtotal = parseFloat(productInfo.value.price);
  const shippingFee = selectedShippingMethod.value.fee;
  const discount = selectedCoupon.value ? parseFloat(selectedCoupon.value.discount) : 0;

  let total = subtotal + shippingFee - discount;
  return Math.max(total, 0).toFixed(2);
};

// 提交订单（含微信支付调用）
const submitOrder = async () => {
  if (!selectedAddress.value) {
    uni.showToast({ title: '请选择收货地址', icon: 'none' });
    return;
  }

  try {
    uni.showLoading({ title: '创建订单中...' });

    // 1. 准备提交给后端的订单数据
    const orderData = {
      orderNumber: orderNumber.value, // 订单号（实际由后端生成时可省略）
      productId: productInfo.value.id,
      productPrice: productInfo.value.price,
      totalAmount: calculateTotal(),
      shippingMethod: selectedShippingMethod.value.id,
      couponId: selectedCoupon.value?.id || '',
      addressId: selectedAddress.value.id || '', // 实际项目中地址应有ID
      sellerId: productInfo.value.userId
    };

    // 2. 调用后端创建订单接口（此处用模拟数据）
    await new Promise(resolve => setTimeout(resolve, 1000));
    const mockPaymentParams = {
      timeStamp: Date.now().toString(),
      nonceStr: 'abcdefghijklmnopqrstuvwxyz123456',
      package: 'prepay_id=wx201410272009395522657a6903892851',
      signType: 'MD5',
      paySign: '70EA570631E4BB79628FBCA90534C63FF7FADD89B001E8F284AC8865A56C'
    };

    uni.hideLoading();

    // 3. 调用微信支付
    uni.requestPayment({
      provider: 'wxpay',
      ...mockPaymentParams,
      success: () => {
        uni.showToast({ title: '支付成功', icon: 'success' });
        setTimeout(() => {
          uni.navigateTo({
            url: `/pages/order-detail/order-detail?orderNumber=${orderNumber.value}`
          });
        }, 1500);
      },
      fail: (err) => {
        console.error('支付失败:', err);
        uni.showToast({ title: err.errMsg.includes('cancel') ? '已取消支付' : '支付失败', icon: 'none' });
      }
    });

  } catch (err) {
    uni.hideLoading();
    uni.showToast({ title: '系统异常，请重试', icon: 'none' });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>


<style scoped>
/* 订单号样式 */
.order-number {
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.order-number .label {
  color: #666;
}

.order-number .value {
  color: #333;
  word-break: break-all;
}
/* 基础样式 */
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

/* 商品信息 */
.product-info {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 20rpx;
}

.product-details {
  width: 100%;
}

.product-title {
  font-size: 32rpx;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  font-size: 34rpx;
  color: #ff4500;
  font-weight: bold;
}

/* 通用区域样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 30rpx;
}

.section-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.address-section, .coupon-section, .shipping-section, .order-summary {
  background-color: #fff;
  margin-bottom: 20rpx;
}

/* 地址区域 */
.address-info {
  padding: 0 30rpx 25rpx 30rpx;
}

.address-name-phone {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.address-name {
  font-size: 30rpx;
  color: #333;
}

.address-phone {
  font-size: 30rpx;
  color: #333;
}

.address-detail {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.no-address {
  padding: 0 30rpx 25rpx 30rpx;
  font-size: 30rpx;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 80rpx;
}

/* 优惠券区域 */
.coupon-selected {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 28rpx;
}

.coupon-list {
  border-top: 1rpx solid #eee;
}

.coupon-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.coupon-item:last-child {
  border-bottom: none;
}

.coupon-left {
  display: flex;
  align-items: center;
}

.coupon-amount {
  font-size: 34rpx;
  color: #ff4500;
  font-weight: bold;
  margin-right: 15rpx;
}

.coupon-desc {
  font-size: 28rpx;
  color: #666;
}

.coupon-right {
  display: flex;
  align-items: center;
}

.coupon-time {
  font-size: 26rpx;
  color: #999;
  margin-right: 10rpx;
}

.no-coupon {
  text-align: center;
  padding: 30rpx 0;
  color: #999;
  font-size: 28rpx;
}

/* 快递方式区域（横向排列） */
.shipping-options {
  display: flex;
  padding: 0 30rpx 25rpx 30rpx;
  overflow-x: auto;
  white-space: nowrap;
}

.shipping-option {
  flex: 1;
  min-width: 200rpx;
  height: 100rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  margin-right: 20rpx;
  padding: 15rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.shipping-option:last-child {
  margin-right: 0;
}

.shipping-option:active {
  background-color: #f5f5f5;
}

.shipping-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.shipping-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.shipping-fee {
  font-size: 26rpx;
  color: #666;
}

/* 订单信息汇总 */
.order-summary {
  padding: 0 30rpx 20rpx 30rpx;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  font-size: 28rpx;
}

.summary-label {
  color: #666;
}

.summary-value {
  color: #333;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 0 10rpx 0;
  margin-top: 10rpx;
  border-top: 1rpx solid #eee;
}

.summary-total .summary-label {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.summary-total .summary-value {
  font-size: 32rpx;
  color: #ff4500;
  font-weight: bold;
}

/* 底部支付栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
}

.total-amount {
  display: flex;
  align-items: center;
}

.total-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 10rpx;
}

.total-value {
  font-size: 34rpx;
  color: #ff4500;
  font-weight: bold;
}

.pay-btn {
  width: 240rpx;
  height: 70rpx;
  background-color: #ff4500;
  color: #fff;
  border-radius: 35rpx;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
}

.pay-btn:disabled {
  background-color: #ffb4a8;
}
</style>